package com.mzj.saas.mservice.qiyuesuo.service;

import com.alibaba.fastjson.JSONObject;
import com.mzj.saas.commons.Constant;
import com.mzj.saas.commons.MD5Utils;
import com.mzj.saas.commons.enums.*;
import com.mzj.saas.config.oss.OssConfig;
import com.mzj.saas.mservice.backlog.entity.BacklogItem;
import com.mzj.saas.mservice.backlog.entity.BacklogItemContractConfirm;
import com.mzj.saas.mservice.backlog.entity.BacklogItemContractSign;
import com.mzj.saas.mservice.backlog.repository.BacklogItemContractConfirmRepository;
import com.mzj.saas.mservice.backlog.repository.BacklogItemContractSignRepository;
import com.mzj.saas.mservice.backlog.repository.BacklogItemRepository;
import com.mzj.saas.mservice.contract.entity.Contract;
import com.mzj.saas.mservice.contract.entity.HouseContractFileRecord;
import com.mzj.saas.mservice.contract.repository.ContractRepository;
import com.mzj.saas.mservice.contract.repository.HouseContractFileRecordRepository;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.oss.service.OSSService;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.redis.RedisService;
import com.qiyuesuo.sdk.v2.utils.CryptUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 契约锁接口
 *
 * @author hp
 */
@Service
public class QiYueSuoService {

    private Logger logger = LoggerFactory.getLogger(QiYueSuoService.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private OssConfig ossConfig;
    @Autowired
    private OSSService ossService;
    @Autowired
    private QiYueSuoContractService qiYueSuoContractService;
    @Autowired
    private ContractRepository contractRepository;
    @Autowired
    private HouseContractFileRecordRepository houseContractFileRecordRepository;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private BacklogItemContractConfirmRepository backlogItemContractConfirmRepository;
	@Autowired
	private BacklogItemContractSignRepository backlogItemContractSignRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    /**
     * 合同回调事件处理
     *
     * @param signature
     * @param timestamp
     * @param content
     * @return
     */
    public String contractCallback(String signature, String timestamp, String content) {
        try {
            logger.info("QiYueSuoService 合同回调事件处理  signature={},timestamp={},content={}", signature, timestamp,
                    content);
            String secretKey = redisService.getValue(Constant.SECRET_KEY);
            String sign = MD5Utils.MD5Encode(timestamp + secretKey, null);

            if (!signature.equals(sign)) {
                secretKey = redisService.getValue(Constant.OWNER_SECRET_KEY);
                sign = MD5Utils.MD5Encode(timestamp + secretKey, null);
                if (!signature.equals(sign)) {
                    logger.error("QiYueSuoService 合同回调事件处理 签名错误");
                    return "success";
                }
            }

            String message = CryptUtils.aesDerypt(content, secretKey);

            if (StringUtils.isBlank(message)) {
                logger.error("QiYueSuoService 合同回调事件处理 无信息 ");
                return "success";
            }

            JSONObject json = JSONObject.parseObject(message);

            logger.info("QiYueSuoService message={}", json.toJSONString());

            String contractId = json.getString("contractId");
            String callbackType = json.getString("callbackType");
            String contractStatus = json.getString("contractStatus");

            logger.info("QiYueSuoService 合同回调结果 contractId={},{}--->{}", contractId,
                    ContractCallbackTypeEnum.operate(callbackType), ContractCallbackStatusEnum.operate(contractStatus));

            // 产权人签署成功
            if (callbackType.equals(ContractCallbackTypeEnum.PERSONAL.getValue())
                    && contractStatus.equals(ContractCallbackStatusEnum.COMPLETE.getValue())) {
                logger.info("QiYueSuoService 合同签章成功, callbackType={}, contractStatus={}", callbackType, contractStatus);
                Contract contract = contractRepository.findByContractId(contractId);
                if (contract == null) {
                    logger.warn("QiYueSuoService 合同回调事件处理 未找到合同信息   contractId={}", contractId);
                    return "success";
                }

                // 已签约待确认
                contract.setStatus(ContractStatusEnum.WAITING_CONFIRMED.getValue());
                contractRepository.save(contract);

                if (contract.getDocumentId() == null) {
                    logger.warn("QiYueSuoService 合同签章成功, 合同文件未下载, documentId为空, contractNubmer={}", contract.getContractNubmer());
                    return "success";
                }

                // 下载合同同步到oss
                File file = qiYueSuoContractService.documentDownload(Long.valueOf(contract.getDocumentId()));
                if (file == null) {
                    logger.warn("QiYueSuoService 合同签章成功, 合同文件下载失败, file为空, documentId={}, contractNubmer={}", contract.getDocumentId(), contract.getContractNubmer());
                    return "success";
                }
                String contractDocUrl = ossService.putFile(ossConfig.getOssBucketName(), file, OSSUploadFileTypeEnum.CONTRACT.toString());
                // 合同文件
                contract.setContractDocUrl(contractDocUrl);
                contractRepository.save(contract);

                // 保存合同文件信息
                HouseContractFileRecord record = new HouseContractFileRecord();
                record.setContractNubmer(contract.getContractNubmer());
                record.setContractId(contract.getContractId());
                record.setDocumentId(contract.getDocumentId());
                record.setContractDocUrl(contractDocUrl);
                record.setCreateTime(new Date());
                houseContractFileRecordRepository.save(record);

                String houseId = contract.getHouseId();
                String matchUserId = contract.getMatchUserId();
                String leaseeName = contract.getLeaseeName();
                Optional<House> houseOptional = houseRepository.findById(houseId);
                House house = houseOptional.get();

				//更新合同待签约待办事项状态
				BacklogItemContractSign contractSign = backlogItemContractSignRepository.findByContractNubmer(contract.getContractNubmer());
				if (contractSign != null) {
					Optional<BacklogItem> backlogItemOpt = backlogItemRepository.findById(contractSign.getBacklogItemId());
					if (backlogItemOpt.isPresent()) {
						BacklogItem item = backlogItemOpt.get();
						item.setBusinessStatus("已签约");
						item.setHandleStatus(1);
						item.setHandlerTime(new Date());
						backlogItemRepository.save(item);
					}
				}
                AppUser appUsers = null;
                if (StringUtils.isNotBlank(matchUserId)){
                     appUsers = appUserRepository.findByIdOrEnterpriseUserId(matchUserId, matchUserId);
                }
                //生成合同待确认待办事项
                BacklogItem backlogItem = new BacklogItem();
                backlogItem.setHouseId(houseId);
                backlogItem.setOrgId(house.getOrgId());
                backlogItem.setType(BacklogItemTypeEnum.CONTRACT_CONFIRM.getValue());
                backlogItem.setTitle(leaseeName + "申请的公租房合同待确认");
                backlogItem.setContent("合同描述：请尽快确认");
                backlogItem.setBusinessStatus("待确认");
                backlogItem.setHandleStatus(0);
                backlogItem.setMatchUserId(matchUserId);
                backlogItem.setPhone(appUsers != null ? appUsers.getPhone() : null);
                backlogItem.setCreateTime(new Date());
                BacklogItem save = backlogItemRepository.save(backlogItem);

                BacklogItemContractConfirm confirm = new BacklogItemContractConfirm();
                confirm.setBacklogItemId(save.getId());
                confirm.setContractNubmer(contract.getContractNubmer());
                backlogItemContractConfirmRepository.save(confirm);

				logger.info("QiYueSuoService 合同签章成功, 处理已完成");
            }
        } catch (Exception e) {
            logger.error("合同事件回调处理异常" + e.getMessage(), e);
        }
        return "success";
    }

    /**
     * 个人认证回调处理
     *
     * @param mode
     * @param status
     * @param authId
     * @return
     */
    public Map<String, Object> personalCallback(String mode, String status, String authId) {
        logger.info("QiYueSuoService 个人认证回调处理,mode={},status={},authId={}", mode, status, authId);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", 0);
        try {

        } catch (Exception e) {
            logger.error("个人认证回调处理异常" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 企业认证回调处理
     *
     * @param status
     * @param requestId
     * @param authInfo
     * @param actionEvent
     * @param response
     * @return
     */
    public Map<String, Object> companyCallback(int status, String requestId, String authInfo, Integer actionEvent) {
        logger.info("QiYueSuoService companyCallback,status={},requestId={},authInfo={},actionEvent={}", status,
                requestId, actionEvent);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", 0);
        try {

        } catch (Exception e) {
            logger.error("企业认证回调处理异常" + e.getMessage(), e);
        }
        return result;
    }

}